import prisma from "@/src/db/db";
import { NextResponse } from "next/server";
import fs from "fs/promises";
export const GET = async (req, { params: { id } }) => {
  const data = await prisma.downloadVerification.findUnique({
    where: { id, expiresAt: { gt: new Date() } },
    select: { product: { select: { filePath: true, name: true } } },
  });
  if (!data) {
    return NextResponse.redirect(
      new URL("/products/download/expired", req.url)
    );
  }
  const { size } = await fs.stat(data.product.filePath);
  const file = await fs.readFile(data.product.filePath);
  const extension = data.product.filePath.split(".").pop();
  return new NextResponse(file, {
    headers: {
      "Content-Disposition": `attachment; filename="${data.product.name}.${extension}"`,
      "Content-Length": size.toString(),
    },
  });
};
